package com.wswy.wzcx.utils;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import com.che.updater.Updater;
import com.che.updater.UpdaterConfig;
import com.wswy.wzcx.BuildConfig;
import com.wswy.wzcx.R;
import com.wswy.wzcx.model.VersionModel;
import com.wswy.wzcx.ui.other.DialogFactory;

/**
 * Created by wangduheng26 on 2018/2/7.
 * wangduheng26@gmail.com
 */

public class UpdateTools {
    public static void start(final Context context, final VersionModel value) {
        DialogFactory.create(context, "发现新版本", value.getDescription(), "更新", "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                updateApp(context,value.getDownloadUrl());
            }
        }).show();
    }

    private static void updateApp(Context context, String url) {
        
        //先从应用宝下载，如果没有安装应用宝，手动从服务器下载
        try {
            if (context.getPackageManager().getPackageInfo("com.tencent.android.qqdownloader",0) != null) {
                Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
                Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                goToMarket.setPackage("com.tencent.android.qqdownloader");
//                goToMarket.setClassName("com.tencent.android.qqdownloader",
//                    "com.tencent.pangu.link.LinkProxyActivity");
                context.startActivity(goToMarket);
            }
        } catch (Throwable e) {

            updateDownload(context, url);

        }


    }


    private static void updateDownload(Context context,String url){
        Resources resources = context.getResources();
        UpdaterConfig config = new UpdaterConfig.Builder(context)
            .setTitle(resources.getString(R.string.app_name))
            .setDescription(resources.getString(R.string.system_download_description))
            .setFileUrl(url)
            .setFilename(BuildConfig.VERSION_NAME+"-update.apk")
            .setCanMediaScanner(true)
            .setIsShowDownloadUI(true)
            .build();
        Updater.get().showLog(true).download(config);
    }

}
